package com.channel.temperature.collect.ui.viewmodel

import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.exception.BluetoothException
import com.hjy.bluetooth.inter.SendCallBack
import com.kongzue.dialogx.dialogs.WaitDialog
import com.channel.temperature.collect.app.dao.OfflineBase
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.ErrorTempData
import com.channel.temperature.collect.data.response.OfflineBean
import com.channel.temperature.collect.data.response.SystemInfoBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.base.appContext
import java.util.ArrayList


class OfflineCollectModel : BaseViewModel() {
    var totalSize = MutableLiveData<Int>()
    var startReadData = MutableLiveData<Boolean>()
    var RoomtotalSizeTips = MutableLiveData<String>()


    var continueSendWakeUpCMD = true
    var clickType = 0
    var continueReadCMD = false

    var packageDataLength: Int = 0
    var packageData: ByteArray = ByteArray(3087)
    var clickDeviceName: String = ""
    var clickDeviceMac: String = ""

    var currentStartLength = 0

    var readFlashSize: Int = 0
    var lastPackageDataSize = 0
    var isLastPackageData = false
    var isTaskOver = MutableLiveData<Boolean>()
    var readListData = ArrayList<OfflineBean>()

    var dataResult: ByteArray = ByteArray(215)
    var otherPackageData = ByteArray(8)
    var taskDeviceName = ""
    var taskCurrentName = ""
    var taskDesc = ""
    var canDownLoad = false
    var exceptionAndFinishActivity = MutableLiveData<Boolean>()
    var canFinished = false


    var readFlash1 = true


    var errorListData = ArrayList<ErrorTempData>()
    var tempTime: Long = 0

    var currentStartLengthList = ArrayList<Int>()
    var errorDataCurrentStartLength = 0//当前要发送的错误数据对应的另外一个存储区的当前位置
    var currentStartLengthListPosition = 0//currentStartLengthList要发送数据的对应位置position

    var readMode = 1//1:快速读取模式 2：安全读取模式
    var mode2HaveReadFlash2 = false//安全读取模式下是否读取了第二包数据

    var flash1SizeTemp = 0
    var flash2SizeTemp = 0

    var flash1FirstTimeTemp: Long = 0
    var flash2FirstTimeTemp: Long = 0

    var currentTimeLong: Long = 0
    var dataResultDesc: String = ""//设备名称 任务名称 任务备注 开始时间 结束时间 组合
    fun sendCommonCMD(value: String) {
        viewModelScope.launch {
            var bufData = MyUtil.hex2Bytes(value)
            HBluetooth.getInstance().send(bufData, object : SendCallBack {
                override fun onSending(command: ByteArray) {
                    Log.e("onSendFailure", "命令发送中... " + MyUtil.bytes2Hex(command))
                }

                override fun onSendFailure(bleException: BluetoothException) {
                    Log.e("onSendFailure", "onSendFailure " + bleException.message.toString())
                }
            })
        }
    }

    fun getparameter() {
        viewModelScope.launch {
            if (HBluetooth.getInstance().isConnected) {
                HBluetooth.getInstance().sender()?.let { it1 ->
                    clickType = 14
                    delay(200)
                    var cmd = "FF55AA000A" + getAddress() + "450100001274004D"
                    sendCommonCMD(
                        cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                    )
                }
            } else {
                ToastUtils.show("请先连接设备后再操作")
            }
        }
    }

    fun handleBLEResult(data: ByteArray) {
        if (data.size > 2) {
            when (clickType) {
                //1:复位 2：关机 3：唤醒设备 4：进入休眠 5：校时 6：清空flash 7：读取存储数量 8:设备信息 9:读系统参数 10：写系统参数 14:读校准系数 12:读离线数据 201：错误数据的位置和时间参数，去读另外一个存储区的当前值
                //202 安全模式（读2个存储区的第一包数据，比较哪个时间最早，就选择哪个存储区）
                9 -> {
                    viewModelScope.launch {
                        var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                        if ("FF55AA" == hexResult) {
                            Log.e("执行了这里", "执行了这里")
                            var dataHex = MyUtil.bytes2Hex(data)
                            var address = dataHex.substring(28, 30).toInt(16)
                            var outTime = dataHex.substring(30, 32).toInt(16)
                            outTime = 30
                            var intervalTime = dataHex.substring(32, 34).toInt(16)
                            var workMode = dataHex.substring(34, 36).toInt(16)
                            var onlineWorkTime = dataHex.substring(36, 40).toInt(16)
                            var onlineWorkInterval = dataHex.substring(40, 44).toInt(16)
                            var mSystemData = SystemInfoBean(
                                address,
                                outTime,
                                intervalTime,
                                workMode,
                                onlineWorkTime,
                                onlineWorkInterval
                            )
                            var json = Gson().toJson(mSystemData)
                            mmkv.putString(ValueKey.SYSTEM_INFO, json)
                            mmkv.putInt(ValueKey.DEVICE_ADDRESS, address)
                            if (workMode == 0) {
                                ToastUtils.show("当前模式已经是待机模式")
                                delay(300)
                                readTotalSize(false)
                            } else {
                                ToastUtils.show("当前不是待机模式,请在系统设置里切换成待机模式后再操作")
                            }
                        }
                    }
                }


                7 -> {

                    var dataHex = MyUtil.bytes2Hex(data)

                    Log.e(
                        "测试",
                        "测试 读取存储的总大小 " + readFlashSize + "  尾包数据 " + lastPackageDataSize
                    )
                    var flash2Size =
                        dataHex.substring(dataHex.length - 10, dataHex.length - 2).toInt(16)

                    var flash1Size =
                        dataHex.substring(dataHex.length - 26, dataHex.length - 18).toInt(16)

                    var totalSize =
                        "" + (dataHex.substring(dataHex.length - 42, dataHex.length - 34).toInt(16)
                            .toDouble() / 1024.0) + "KB"
                    flash1SizeTemp = flash1Size
                    flash2SizeTemp = flash2Size
                    viewModelScope.launch {
                        if (readMode == 1) {
                            if (flash1Size <= flash2Size) {
                                readFlash1 = true
                                Log.e("判断", "判断1111111111 " + readFlash1)
                                readFlashSize = flash1Size
                                lastPackageDataSize = readFlashSize % 3072
                                RoomtotalSizeTips.value =
                                    "读取到设备已存储总条数：" + flash1Size / 32
                            } else {
                                readFlash1 = false
                                readFlashSize = flash2Size
                                lastPackageDataSize = readFlashSize % 3072
                                Log.e("判断", "判断22222222 " + readFlash1)
                                RoomtotalSizeTips.value =
                                    "读取到设备已存储总条数：" + flash2Size / 32
                            }
                        } else if (readMode == 2) {

                            mode2HaveReadFlash2 = false
                            //先读存储1的flash的第一包3K数据
                            clickType = 202
                            packageDataLength = 0
                            packageData = ByteArray(3087)
                            var cmd =
                                "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                    0, true
                                ) + "0C00"

                            sendCommonCMD(
                                cmd + CRC16Utils.checkCRC(
                                    MyUtil.hex2Bytes(
                                        cmd
                                    )
                                )
                            )

                        }
                    }


                }

                14 -> {
                    Log.e(
                        "参数14",
                        "参数14返回数据 ： " + MyUtil.bytes2Hex(data) + " 数据长度 " + MyUtil.bytes2Hex(
                            data
                        ).length
                    )
                    viewModelScope.launch {
                        var result = CRC16Utils.checkCRC(data.copyOfRange(0, data.size - 1))
                        if (MyUtil.bytes2Hex(data)
                                .contains("FF55AA") && result.toInt(16) == java.lang.Byte.toUnsignedInt(
                                data[data.size - 1]
                            ) && CRC16Utils.CHECKSUM(data.copyOfRange(14, 90)).toInt(16)
                            == java.lang.Byte.toUnsignedInt(
                                data[data.size - 2]
                            )
                        ) {

                            Log.e("参数14", "校验通过 ： ")

                            var rationResult = MyUtil.bytes2Hex(data.copyOfRange(14, 90))
                            Log.e("参数14", "参数14  ： " + rationResult)
                            if (rationResult.contains("FFFFFF")) {
                                ToastUtils.show("本设备未校准，请先联系技术人员")
                            } else {
                                mmkv.putString(ValueKey.RATIO_KEY, rationResult)
                                ToastUtils.show("获取当前数据计算参数成功")
                                canDownLoad = true
                            }

                        } else {
                            ToastUtils.show("参数校验未通过")
                        }
                        resetClickType()
                    }
                }

                202 -> {
                    try {
                        viewModelScope.launch {
                            if (packageDataLength < 3087) {
                                System.arraycopy(
                                    data, 0, packageData, packageDataLength, data.size
                                )
                                packageDataLength += data.size
                            }

                            if (packageDataLength == 3087) {
                                if (CRC16Utils.checkCRC(
                                        packageData.copyOfRange(
                                            0, packageData.size - 1
                                        )
                                    )
                                        .toInt(16) == java.lang.Byte.toUnsignedInt(packageData[packageData.size - 1])
                                ) {
                                    //完整数据
                                    var listSize = ((packageDataLength - 15) / 32)
                                    var tempPackageData = packageData.copyOfRange(
                                        14, packageDataLength - 1
                                    )
                                    var packageListData =
                                        getDataResultListByUncheck(listSize, tempPackageData)

                                    if (mode2HaveReadFlash2 == false) {
                                        if (packageListData.size > 0) {
                                            flash1FirstTimeTemp =
                                                packageListData[0].time.split("&").get(0)
                                                    .toLong()
                                            Log.e(
                                                "安全模式",
                                                "安全模式 flash1的第一个是时间值 " + flash1FirstTimeTemp
                                            )
                                        }
                                        mode2HaveReadFlash2 = true
                                        packageDataLength = 0
                                        packageData = ByteArray(3087)
                                        clickType = 202
                                        var cmd =
                                            "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                                0, false
                                            ) + "0C00"
                                        sendCommonCMD(
                                            cmd + CRC16Utils.checkCRC(
                                                MyUtil.hex2Bytes(
                                                    cmd
                                                )
                                            )
                                        )
                                    } else {
                                        if (packageListData.size > 0) {
                                            flash2FirstTimeTemp =
                                                packageListData[0].time.split("&").get(0)
                                                    .toLong()
                                            Log.e(
                                                "安全模式",
                                                "安全模式 flash2的第二个时间值 " + flash2FirstTimeTemp
                                            )
                                            resetClickType()
                                            if (flash1FirstTimeTemp <= flash2FirstTimeTemp) {
                                                readFlash1 = true
                                                Log.e("判断", "判断1111111111 " + readFlash1)
                                                readFlashSize = flash1SizeTemp
                                                lastPackageDataSize = readFlashSize % 3072
                                                RoomtotalSizeTips.value =
                                                    "读取到设备已存储总条数：" + readFlashSize / 32
                                            } else {
                                                readFlash1 = false
                                                Log.e("判断", "判断1111111111 " + readFlash1)
                                                readFlashSize = flash2SizeTemp
                                                lastPackageDataSize = readFlashSize % 3072
                                                RoomtotalSizeTips.value =
                                                    "读取到设备已存储总条数：" + readFlashSize / 32
                                            }
                                        }
                                    }

                                }

                            }
                        }
                    } catch (e: ArrayIndexOutOfBoundsException) {
                        canFinished = true
                        exceptionAndFinishActivity.value = true
                    }
                }

                201 -> {
                    try {
                        viewModelScope.launch {
                            if (packageDataLength < 3087) {
                                System.arraycopy(
                                    data, 0, packageData, packageDataLength, data.size
                                )
                                packageDataLength += data.size
                            }

                            if (packageDataLength == 3087) {
                                if (CRC16Utils.checkCRC(
                                        packageData.copyOfRange(
                                            0, packageData.size - 1
                                        )
                                    )
                                        .toInt(16) == java.lang.Byte.toUnsignedInt(packageData[packageData.size - 1])
                                ) {
                                    //完整数据
                                    var listSize = ((packageDataLength - 15) / 32)
                                    var tempPackageData = packageData.copyOfRange(
                                        14, packageDataLength - 1
                                    )
                                    var packageListData =
                                        getDataResultListByUncheck(listSize, tempPackageData)

                                    if (packageListData.size > 0) {
                                        for (i in 0 until errorListData.size) {
                                            if (errorListData[i].currentReadLength == errorDataCurrentStartLength) {
                                                var time = errorListData[i].time
                                                for (i in 0 until packageListData.size) {
                                                    var bean =
                                                        packageListData[i].time.split("&").get(0)
                                                            .toLong()
                                                    if (time == bean) {
                                                        if (i < packageListData.size - 2) {
                                                            readListData.add(packageListData.get(i + 1))
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                    if (currentStartLengthListPosition + 1 >= currentStartLengthList.size) {
                                        Log.e("错误数据", "错误数据全剧终")
                                        startInsertToRoom()
                                        ToastUtils.show("离线数据下载完毕")
                                        stopTimeTask()
                                        isTaskOver.value = true
                                        continueReadCMD = false
                                        resetClickType()
                                    } else {
                                        Log.e("错误数据", "错误数据继续来")
                                        currentStartLengthListPosition++
                                        packageDataLength = 0
                                        packageData = ByteArray(3087)
                                        if (continueReadCMD) {
                                            errorDataCurrentStartLength =
                                                currentStartLengthList[currentStartLengthListPosition]
                                            var cmd =
                                                "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                                    errorDataCurrentStartLength, !readFlash1
                                                ) + "0C00"
                                            restartTimeTask()

                                            sendCommonCMD(
                                                cmd + CRC16Utils.checkCRC(
                                                    MyUtil.hex2Bytes(
                                                        cmd
                                                    )
                                                )
                                            )
                                        }
                                    }

                                }
                            }
                        }
                    } catch (e: ArrayIndexOutOfBoundsException) {
                        canFinished = true
                        exceptionAndFinishActivity.value = true
                    }
                }

                12 -> {
                    Log.e("handleBLEResult", " " + data.size)
                    try {
                        viewModelScope.launch {
                            if (isLastPackageData == false) {
                                if (packageDataLength < 3087) {
                                    System.arraycopy(
                                        data, 0, packageData, packageDataLength, data.size
                                    )
                                    packageDataLength += data.size
                                }

                                if (packageDataLength == 3087) {
                                    if (CRC16Utils.checkCRC(
                                            packageData.copyOfRange(
                                                0, packageData.size - 1
                                            )
                                        )
                                            .toInt(16) == java.lang.Byte.toUnsignedInt(packageData[packageData.size - 1])
                                    ) {
                                        if (currentStartLength != readFlashSize - lastPackageDataSize - 3072) {
                                            synchronized(lock) {
                                                //完整数据
                                                var listSize = ((packageDataLength - 15) / 32)
                                                var tempPackageData = packageData.copyOfRange(
                                                    14, packageDataLength - 1
                                                )
                                                var packageListData =
                                                    getDataResultList(listSize, tempPackageData)

                                                var tempSize: Int = totalSize.value as Int
                                                totalSize.value = tempSize + packageListData.size
                                                Log.e(
                                                    "要添加", "要添加的长度 " + packageListData.size
                                                )
                                                for (i in 0 until packageListData.size) {
                                                    readListData.add(packageListData.get(i))
                                                }

                                                packageDataLength = 0
                                                packageData = ByteArray(3087)
                                                if (continueReadCMD) {
                                                    restartTimeTask()
                                                    currentStartLength = currentStartLength + 3072
                                                    Log.e(
                                                        "结果", "结果 ：" + currentStartLength
                                                    )
                                                    var cmd =
                                                        "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                                            currentStartLength, readFlash1
                                                        ) + "0C00"

                                                    sendCommonCMD(
                                                        cmd + CRC16Utils.checkCRC(
                                                            MyUtil.hex2Bytes(
                                                                cmd
                                                            )
                                                        )
                                                    )
                                                }
                                            }


                                        } else {
                                            Log.e("存储倒数第二包", "存储倒数第二包")
                                            synchronized(lock) {
                                                //完整数据
                                                var listSize = ((packageDataLength - 15) / 32)
                                                var tempPackageData = packageData.copyOfRange(
                                                    14, packageDataLength - 1
                                                )
                                                var packageListData =
                                                    getDataResultList(listSize, tempPackageData)
                                                Log.e(
                                                    "要添加", "要添加的长度 " + packageListData.size
                                                )
                                                for (i in 0 until packageListData.size) {
                                                    readListData.add(packageListData.get(i))
                                                }
                                                Log.e(
                                                    "要发最后一包数据了最后一包数据了",
                                                    "要发最后一包数据了"
                                                )
                                                if (continueReadCMD) {
                                                    isLastPackageData = true
                                                    if (lastPackageDataSize > 0) {
                                                        var byteArraySize = 15 + lastPackageDataSize
                                                        Log.e(
                                                            "最后一包完整数据的长度",
                                                            "最后一包完整数据的长度 " + byteArraySize
                                                        )
                                                        var tempSize: Int = totalSize.value as Int
                                                        totalSize.value =
                                                            tempSize + packageListData.size
                                                        packageData = ByteArray(byteArraySize)
                                                        restartTimeTask()
                                                        currentStartLength =
                                                            currentStartLength + 3072
                                                        packageDataLength = 0
                                                        var cmd =
                                                            "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                                                currentStartLength, readFlash1
                                                            ) + MyUtil.numberToHexTwo(
                                                                lastPackageDataSize
                                                            )
                                                        Log.e(
                                                            "当前位置",
                                                            "最后一包 当前位置 : " + currentStartLength + "     " + currentStartLengthToHex(
                                                                currentStartLength, readFlash1
                                                            )
                                                        )
                                                        sendCommonCMD(
                                                            cmd + CRC16Utils.checkCRC(
                                                                MyUtil.hex2Bytes(
                                                                    cmd
                                                                )
                                                            )
                                                        )
                                                    } else {
                                                        startInsertToRoom()
                                                        ToastUtils.show("离线数据下载完毕")
                                                        stopTimeTask()
                                                        isTaskOver.value = true
                                                        continueReadCMD = false
                                                        resetClickType()
                                                    }

                                                }
                                            }

                                        }
                                    } else {
                                        Log.e("校验未通过", "校验未通过，500毫秒后重发")
                                    }
                                } else if (packageDataLength > 3087) {
                                    Log.e(
                                        "下载离线数据返回异常",
                                        "处理返回的数据结果异常 500毫秒后重发"
                                    )
                                    delay(300)
                                    packageDataLength = 0
                                    packageData = ByteArray(3087)
                                    if (continueReadCMD) {
                                        restartTimeTask()
                                        currentStartLength = currentStartLength
                                        Log.e(
                                            "结果", "结果 ：" + currentStartLength
                                        )
                                        var cmd =
                                            "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                                currentStartLength, readFlash1
                                            ) + "0C00"

                                        sendCommonCMD(
                                            cmd + CRC16Utils.checkCRC(
                                                MyUtil.hex2Bytes(
                                                    cmd
                                                )
                                            )
                                        )
                                    }
                                }
                            } else {

                                if (lastPackageDataSize > 0) {
                                    System.arraycopy(
                                        data, 0, packageData, packageDataLength, data.size
                                    )
                                    packageDataLength += data.size
                                    if (packageDataLength == lastPackageDataSize + 15) {
                                        synchronized(lock) {
                                            var listSize = ((packageDataLength - 15) / 32)
                                            var tempPackageData =
                                                packageData.copyOfRange(14, packageDataLength - 1)
                                            var packageListData =
                                                getDataResultList(listSize, tempPackageData)
                                            for (i in 0 until packageListData.size) {
                                                readListData.add(packageListData.get(i))
                                            }
                                            Log.e("最终", "最终总长度 " + readListData.size)
                                            startInsertToRoom()


                                            var tempSize: Int = totalSize.value as Int
                                            totalSize.value = tempSize + listSize
                                            Log.e(
                                                "测试",
                                                "最终总长度   ： " + OfflineBase.get(appContext)
                                                    .offlineDao().queryRoomCount()
                                            )
                                            Log.e(
                                                "下载完毕",
                                                "下载完毕，错误数据列表 " + errorListData.size
                                            )
                                            if (errorListData.size > 0) {
                                                getDataOfOtherFlash()
                                            } else {
                                                ToastUtils.show("离线数据下载完毕")
                                                stopTimeTask()
                                                isTaskOver.value = true
                                                continueReadCMD = false
                                                resetClickType()
                                            }

                                        }
                                    }
                                } else {
                                    startInsertToRoom()

                                    Log.e(
                                        "下载完毕", "下载完毕，错误数据列表 " + errorListData.size
                                    )
                                    if (errorListData.size > 0) {
                                        getDataOfOtherFlash()
                                    } else {
                                        ToastUtils.show("离线数据下载完毕")
                                        stopTimeTask()
                                        isTaskOver.value = true
                                        continueReadCMD = false
                                        resetClickType()
                                    }
                                }

                            }
                        }
                    } catch (e: ArrayIndexOutOfBoundsException) {
                        canFinished = true
                        exceptionAndFinishActivity.value = true
                    }
                }
            }
        }
    }


    private fun getDataOfOtherFlash() {
        currentStartLengthList.clear()
        errorDataCurrentStartLength = 0
        currentStartLengthListPosition = 0
        for (i in 0 until errorListData.size) {
            if (!currentStartLengthList.contains(errorListData[i].currentReadLength)) {
                currentStartLengthList.add(errorListData[i].currentReadLength)
            }
        }
        clickType = 201
        packageDataLength = 0
        packageData = ByteArray(3087)
        if (continueReadCMD) {
            restartTimeTask()
            errorDataCurrentStartLength = currentStartLengthList[0]
            currentStartLengthListPosition = 0
            var cmd = "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                currentStartLengthList[0], !readFlash1
            ) + "0C00"

            sendCommonCMD(
                cmd + CRC16Utils.checkCRC(
                    MyUtil.hex2Bytes(
                        cmd
                    )
                )
            )
        }
    }

    fun startInsertToRoom() {
        viewModelScope.launch {
            WaitDialog.show("正在向本地写入数据，请等待")
            delay(100)
            val result = withContext(Dispatchers.IO) {
                for (i in 0 until readListData.size) {
                    var mBean = readListData.get(i)
                    var gx = mBean.gX2
                    var pt2 = mBean.pT2
                    var pressure = mBean.pressure2
                    if (gx.isNaN() || pt2.isNaN() || pressure.isNaN()) {
                        Log.e("正在插入数据", " 出现错误数据 " + readListData.get(i))
                    } else {
                        OfflineBase.get(appContext).offlineDao().insert(mBean)
                    }
                    if (i == readListData.size - 1) {
                        var key = "$taskDeviceName&$currentTimeLong"
                        mmkv.putString(key, dataResultDesc)
                        Log.e("测试值", key + "   测试值   " + mmkv.getString(key, ""))
                        WaitDialog.dismiss(1000)
                        ToastUtils.show("数据处理成功")
                    }
                }
                "数据处理成功"
            }


        }

    }


    public fun getDataResultList(
        listSize: Int, tempPackageData: ByteArray
    ): ArrayList<OfflineBean> {
        Log.e("getDataResultList", "getDataResultList   " + MyUtil.bytes2Hex(tempPackageData))
        var packageListData = ArrayList<OfflineBean>()
        for (i in 0 until listSize) {
            var dataBytes = tempPackageData.copyOfRange(i * 32, (i + 1) * 32)
            if (dataBytes[dataBytes.size - 1] == 0x5A.toByte()) {
                var time = MyUtil.bytesToInt(dataBytes.copyOfRange(0, 4)).toLong()
                tempTime = time
                var deviceName = taskDeviceName
                var deviceMac = clickDeviceMac
                var result = MyUtil.bytes2Hex(dataBytes)

//                var gx1 = result.substring(12, 16).toInt(16).toFloat()
                var gx2 = result.substring(16, 20).toInt(16).toFloat()


                var pt1Temp =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(20, 28))).toFloat()
                var pt2Temp =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(28, 36))).toFloat()
                var voltage =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(52, 60))).toFloat()
//                var pressure1 =
//                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(36, 44))).toFloat()
                var pressure2 =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(44, 52))).toFloat()


                var dataRatio = MyUtil.hex2Bytes(mmkv.getString(ValueKey.RATIO_KEY, ""))


                var PT1Temperature1 = getPT1000Temperature(pt1Temp, voltage)
                var PT1Temperature2 = getPT1000Temperature(pt2Temp, voltage)

                var pressure2Temp = getPressureByPT1AndPressure2(
                    PT1Temperature1, pressure2
                )

                var pressure2ResultTemp = MyUtil.formatFloat(pressure2Temp, 3, 0.000f)
                var pressure2Result = 0.000f
                if ("-∞" == pressure2ResultTemp || "∞" == pressure2ResultTemp) {
                    pressure2Result = 0.000f
                } else {
                    pressure2Result = pressure2ResultTemp.toFloat()
                    pressure2Result = if (pressure2Result > 100f) 100f else pressure2Result
                }
                var mBean = OfflineBean(
                    deviceName = "$deviceName&$currentTimeLong",
                    deviceMac = deviceMac,
                    dataResult = result,
                    time = "$time&$deviceName&$currentTimeLong",
                    currentTaskName = taskCurrentName,
                    gX2 = gx2 / 100f,
                    pT2 = PT1Temperature2,
                    pressure2 = MyUtil.formatFloat(
                        pressure2Result, 3, 0.000f
                    ).toFloat()
                )
                packageListData.add(mBean)
            } else {
                if (!MyUtil.bytes2Hex(dataBytes).contains("FFFFFFFF")) {
                    errorListData.add(ErrorTempData(currentStartLength, tempTime))
                    Log.e("错误数据", "错误数据")
                }

            }
        }
        return packageListData
    }

    public fun getDataResultListByUncheck(
        listSize: Int, tempPackageData: ByteArray
    ): ArrayList<OfflineBean> {
        Log.e("getDataResultList", "getDataResultList   " + MyUtil.bytes2Hex(tempPackageData))
        var packageListData = ArrayList<OfflineBean>()
        for (i in 0 until listSize) {
            var dataBytes = tempPackageData.copyOfRange(i * 32, (i + 1) * 32)
            if (dataBytes[dataBytes.size - 1] == 0x5A.toByte()) {
                var time = MyUtil.bytesToInt(dataBytes.copyOfRange(0, 4)).toLong()
                tempTime = time
                var deviceName = taskDeviceName
                var deviceMac = clickDeviceMac
                var result = MyUtil.bytes2Hex(dataBytes)

//                var gx1 = result.substring(12, 16).toInt(16).toFloat()
                var gx2 = result.substring(16, 20).toInt(16).toFloat()


                var pt1Temp =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(20, 28))).toFloat()
                var pt2Temp =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(28, 36))).toFloat()
                var voltage =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(52, 60))).toFloat()
//                var pressure1 =
//                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(36, 44))).toFloat()
                var pressure2 =
                    MyUtil.bytes2Float(MyUtil.hex2Bytes(result.substring(44, 52))).toFloat()


                var dataRatio = MyUtil.hex2Bytes(mmkv.getString(ValueKey.RATIO_KEY, ""))


                var PT1Temperature1 = getPT1000Temperature(pt1Temp, voltage)
                var PT1Temperature2 = getPT1000Temperature(pt2Temp, voltage)

                var pressure2Temp = getPressureByPT1AndPressure2(
                    PT1Temperature1, pressure2
                )

                var pressure2ResultTemp = MyUtil.formatFloat(pressure2Temp, 3, 0.000f)
                var pressure2Result = 0.000f
                if ("-∞" == pressure2ResultTemp || "∞" == pressure2ResultTemp) {
                    pressure2Result = 0.000f
                } else {
                    pressure2Result = pressure2ResultTemp.toFloat()
                    pressure2Result = if (pressure2Result > 100f) 100f else pressure2Result
                }
                var mBean = OfflineBean(
                    deviceName = deviceName,
                    deviceMac = deviceMac,
                    dataResult = result,
                    time = "$time&$deviceName",
                    currentTaskName = taskCurrentName,
                    gX2 = gx2 / 100f,
                    pT2 = PT1Temperature2,
                    pressure2 = MyUtil.formatFloat(
                        pressure2Result, 3, 0.000f
                    ).toFloat()
                )
                packageListData.add(mBean)
            }
        }
        return packageListData
    }

//    public fun getPressureByPT1AndPressure2(pt1: Float, adc: Float): Float {
//
////        var pt1 = 29.990806579589844f
////        var adc = 22030.865234375f
////        Log.e("存储值", "参数 ：" + pt1 + "    " + adc)
//
//        var dataRatio = MyUtil.hex2Bytes(mmkv.getString(ValueKey.RATIO_KEY, ""))
//        var parameter1 = MyUtil.bytes2Double(dataRatio.copyOfRange(0, 8))
//        var parameter2 = MyUtil.bytes2Double(dataRatio.copyOfRange(8, 16))
//        var parameter3 = MyUtil.bytes2Double(dataRatio.copyOfRange(16, 24))
//        var parameter4 = MyUtil.bytes2Double(dataRatio.copyOfRange(24, 32))
//        var parameter5 = MyUtil.bytes2Double(dataRatio.copyOfRange(32, 40))
//        var parameter6 = MyUtil.bytes2Double(dataRatio.copyOfRange(40, 48))
//        var parameter7 = MyUtil.bytes2Double(dataRatio.copyOfRange(48, 56))
//        var parameter8 = MyUtil.bytes2Double(dataRatio.copyOfRange(56, 64))
//        var parameter9 = MyUtil.bytes2Double(dataRatio.copyOfRange(64, 72))
//        var parameter10 = MyUtil.bytes2Double(dataRatio.copyOfRange(72, 80))
//        var parameter11 = MyUtil.bytes2Double(dataRatio.copyOfRange(80, 88))
//        var parameter12 = MyUtil.bytes2Double(dataRatio.copyOfRange(88, 96))
//        var parameter13 = MyUtil.bytes2Double(dataRatio.copyOfRange(96, 104))
//        var parameter14 = MyUtil.bytes2Double(dataRatio.copyOfRange(104, 112))
//        var parameter15 = MyUtil.bytes2Double(dataRatio.copyOfRange(112, 120))
////        var parameter1 = 469.757
////        var parameter2 = 0.772
////        var parameter3 = 0.251
////        var parameter4 = 0.054
////        var parameter5 = 0
////        var parameter6 = 0
////        var parameter7 = -0.001
////        var parameter8 = 0
////        var parameter9 = 0
////        var parameter10 = 0
////        var parameter11 = 0
////        var parameter12 = 0
////        var parameter13 = 0
////        var parameter14 = 0
////        var parameter15 = 0
////        var y = parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
////            pt1.toDouble(), 2.0
////        ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
////            pt1.toDouble(), 2.0
////        ) * adc + parameter9 * pt1 * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
////            pt1.toDouble(), 3.0
////        ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
////            pt1.toDouble(), 4.0
////        ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0)
//
////        + parameter5 * pt1 * adc + parameter6 * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
////            pt1.toDouble(), 2.0
////        ) * adc + parameter9 * pt1 * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
////            pt1.toDouble(), 3.0
////        ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
////            adc.toDouble(), 2.0
////        ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
////            pt1.toDouble(), 4.0
////        ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0)
////        Log.e("存储值", "结果 ：" + y.toFloat())
//
//        if (pt1 >= 50.0f) {
//            var y = (parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
//                pt1.toDouble(), 2.0
//            ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
//                pt1.toDouble(), 2.0
//            ) * adc + parameter9 * pt1 * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
//                pt1.toDouble(), 3.0
//            ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
//                pt1.toDouble(), 4.0
//            ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0))
//            var result =
//                5.811 + (-0.089 * pt1) + (-0.005 * y) + 0.001 * Math.pow(pt1.toDouble(), 2.0);
//            return ((y - result).toFloat()) / 100.0f
//        } else {
//            var y = (parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
//                pt1.toDouble(), 2.0
//            ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
//                pt1.toDouble(), 2.0
//            ) * adc + parameter9 * pt1 * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
//                pt1.toDouble(), 3.0
//            ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
//                adc.toDouble(), 2.0
//            ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
//                pt1.toDouble(), 4.0
//            ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(
//                adc.toDouble(),
//                2.0
//            )) / 100.0f
//            return y.toFloat()
//        }
//
//    }

    public fun getPressureByPT1AndPressure2(pt1: Float, adc: Float): Float {

//        var pt1 = 29.990806579589844f
//        var adc = 22030.865234375f
//        Log.e("存储值", "参数 ：" + pt1 + "    " + adc)

        var dataRatio = MyUtil.hex2Bytes(mmkv.getString(ValueKey.RATIO_KEY, ""))
        var parameter1 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(0, 4)).toFloat()
        var parameter2 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(4, 8)).toDouble()
        var parameter3 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(8, 12)).toDouble()
        var parameter4 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(12, 16)).toFloat()
        var parameter5 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(16, 20)).toFloat()
        var parameter6 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(20, 24)).toFloat()
        var parameter7 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(24, 28)).toFloat()
        var parameter8 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(28, 32)).toFloat()
        var parameter9 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(32, 36)).toFloat()
        var parameter10 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(36, 40)).toFloat()
        var parameter11 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(40, 44)).toFloat()
        var parameter12 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(44, 48)).toFloat()
        var parameter13 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(48, 52)).toFloat()
        var parameter14 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(52, 56)).toFloat()
        var parameter15 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(56, 60)).toFloat()
        var parameter16 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(60, 64)).toFloat()
        var parameter17 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(64, 68)).toFloat()
        var parameter18 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(68, 72)).toFloat()
        var parameter19 = MyUtil.bytes2FloatOther(dataRatio.copyOfRange(72, 76)).toFloat()
//        var parameter1 = 469.757
//        var parameter2 = 0.772
//        var parameter3 = 0.251
//        var parameter4 = 0.054
//        var parameter5 = 0
//        var parameter6 = 0
//        var parameter7 = -0.001
//        var parameter8 = 0
//        var parameter9 = 0
//        var parameter10 = 0
//        var parameter11 = 0
//        var parameter12 = 0
//        var parameter13 = 0
//        var parameter14 = 0
//        var parameter15 = 0
//        var y = parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
//            pt1.toDouble(), 2.0
//        ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
//            pt1.toDouble(), 2.0
//        ) * adc + parameter9 * pt1 * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
//            pt1.toDouble(), 3.0
//        ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
//            pt1.toDouble(), 4.0
//        ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0)

//        + parameter5 * pt1 * adc + parameter6 * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
//            pt1.toDouble(), 2.0
//        ) * adc + parameter9 * pt1 * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
//            pt1.toDouble(), 3.0
//        ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
//            adc.toDouble(), 2.0
//        ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
//            pt1.toDouble(), 4.0
//        ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0)
//        Log.e("存储值", "结果 ：" + y.toFloat())

        if (pt1 >= 50.0f) {
            var y = (parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
                pt1.toDouble(), 2.0
            ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
                pt1.toDouble(), 2.0
            ) * adc + parameter9 * pt1 * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
                pt1.toDouble(), 3.0
            ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
                pt1.toDouble(), 4.0
            ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(adc.toDouble(), 2.0))
            var result =
                parameter16 + (parameter17 * pt1) + (parameter18 * y) + parameter19 * Math.pow(
                    pt1.toDouble(), 2.0
                );
            return ((y - result).toFloat()) / 100.0f
        } else {
            var y = (parameter1 + parameter2 * pt1 + parameter3 * adc + parameter4 * Math.pow(
                pt1.toDouble(), 2.0
            ) + parameter5 * pt1 * adc + parameter6 * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter7 * Math.pow(pt1.toDouble(), 3.0) + parameter8 * Math.pow(
                pt1.toDouble(), 2.0
            ) * adc + parameter9 * pt1 * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter10 * Math.pow(pt1.toDouble(), 4.0) + parameter11 * Math.pow(
                pt1.toDouble(), 3.0
            ) * adc + parameter12 * Math.pow(pt1.toDouble(), 2.0) * Math.pow(
                adc.toDouble(), 2.0
            ) + parameter13 * Math.pow(pt1.toDouble(), 5.0) + parameter14 * Math.pow(
                pt1.toDouble(), 4.0
            ) * adc + parameter15 * Math.pow(pt1.toDouble(), 3.0) * Math.pow(
                adc.toDouble(), 2.0
            )) / 100.0f
            return y.toFloat()
        }

    }


    /**
     * gxTemperature gx温度
     * voltage 基准电阻
     */
    fun getPT1000Temperature(gxTemperature: Float, voltage: Float): Float {
        var Rt = gxTemperature / voltage * 1000f
        var PT1000_A = 0.0039083f
        var PT1000_B = -0.0000005775f
        var PT1000_R = 1000f
        var temp: Float
        temp = PT1000_A * PT1000_A - 4 * PT1000_B * (PT1000_R - Rt) / PT1000_R
        temp = Math.sqrt(temp.toDouble()).toFloat()
        temp = temp - PT1000_A
        temp = temp / (2 * PT1000_B)
        return temp
    }


    var lock = Object()

    var countDownTimer: CountDownTimer? = null
    var resendCount: Int = 0
    fun startCheckTimeOut() {
        viewModelScope.launch {
            countDownTimer = object : CountDownTimer(4000, 1000) {
                override fun onFinish() {
                    Log.e("倒计时结束", "==倒计时结束")
                    var isOver = isTaskOver.value
                    if (isOver == false) {
                        if (packageDataLength != 0 || packageDataLength != 3087) {
                            Log.e("重新发送当前数据", "重新发送当前数据")
                            //时间到了 数据异常，重新发送一次当前包的数据
                            resendCount++
                            if (resendCount == 3) {
                                resendCount = 0
                                ToastUtils.show("下载数据异常，请重试")
                                packageDataLength = 0
                                isTaskOver.value = true
                            } else {
                                restartTimeTask()
                                packageDataLength = 0

                                if (!isLastPackageData) {
                                    packageData = ByteArray(3087)
                                    var cmd =
                                        "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                            currentStartLength, readFlash1
                                        ) + "0C00"
                                    sendCommonCMD(
                                        cmd + CRC16Utils.checkCRC(
                                            MyUtil.hex2Bytes(
                                                cmd
                                            )
                                        )
                                    )
                                } else {
                                    var byteArraySize = 15 + lastPackageDataSize
                                    packageData = ByteArray(byteArraySize)
                                    var cmd =
                                        "FF55AA000A" + getAddress() + "4101" + currentStartLengthToHex(
                                            currentStartLength, readFlash1
                                        ) + MyUtil.numberToHexTwo(
                                            lastPackageDataSize
                                        )
                                    sendCommonCMD(
                                        cmd + CRC16Utils.checkCRC(
                                            MyUtil.hex2Bytes(
                                                cmd
                                            )
                                        )
                                    )
                                }

                            }

                        }
                    } else {
                        Log.e("倒计时结束", "倒计时结束，最后一包数据也发完拉")
                    }

                }

                override fun onTick(millisUntilFinished: Long) {
                    var second = millisUntilFinished / 1000 % 60
                    Log.e("正在倒计时", "==倒计时" + second + "秒")
                }
            }.start()
        }
    }

    private fun readTotalSize(clearFirst: Boolean) {
        //读取当前存储数量
        if (HBluetooth.getInstance().isConnected) {
            if (clearFirst) {
                OfflineBase.get(appContext).offlineDao().deleteAll()
            }
            HBluetooth.getInstance().sender()?.let { it1 ->
                clickType = 7
                var cmd = "FF55AA0003" + getAddress() + "44"
                sendCommonCMD(
                    cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                )
            }
        } else {
            ToastUtils.show("请先连接设备后再操作")
        }
    }

    fun restartTimeTask() {
        countDownTimer?.cancel()
        countDownTimer?.start()
    }

    fun stopTimeTask() {
        countDownTimer?.cancel()

    }


    fun getAddress(): String {
        return "FA"
    }

    public fun resetClickType() {
        clickType = -1
    }

    /**
     *isFlash1:true 读的存储1  false: isFlash读的存储2
     */
    fun currentStartLengthToHex(number: Int, isFlash1: Boolean): String? {
        var result = MyUtil.bytes2Hex(MyUtil.intToBytes(number))
        if (!isFlash1) {
            return "80" + result.substring(2, 8)
        }
        return result
    }
}


